// 房间结算查看页面
const app = getApp()
const RoomUtils = require('../../utils/roomUtils.js')

Page({
  data: {
    roomInfo: null,
    settlementData: null,
    loading: false,
    hasSettlement: false,
    mySettlement: null,
    otherSettlements: [],
    myDetailsExpanded: false, // 默认折叠自己的详情
    settlementSummary: [] // 结算策略总结
  },

  onLoad(options) {
    // 从参数或缓存获取房间信息
    const roomId = options.room_id
    if (roomId) {
      this.setData({ roomInfo: { id: roomId } })
      this.getRoomSettlement()
    } else {
      this.checkRoomFromCache()
    }
    
    // 监听WebSocket消息，处理自动跳转
    this.setupWebSocketListener()
  },

  onShow() {
    // 每次显示时重新检查
    if (this.data.roomInfo) {
      this.getRoomSettlement()
    }
  },

  // 从缓存检查房间信息
  checkRoomFromCache() {
    const RoomCache = require('../../utils/roomCache')
    const roomData = RoomCache.getRoomBasicInfo()

    if (!roomData) {
      wx.showModal({
        title: '无法查看结算',
        content: '请先加入房间',
        showCancel: false,
        confirmText: '确定',
        success: () => {
          wx.navigateBack({
            delta: 1
          })
        }
      })
      return
    }

    this.setData({
      roomInfo: roomData
    })
    this.getRoomSettlement()
  },

  // 获取房间结算数据
  getRoomSettlement() {
    if (!this.data.roomInfo) {
      return
    }

    this.setData({ loading: true })

    wx.request({
      url: `${app.globalData.baseUrl}/api/accounting/room-settlement`,
      method: 'GET',
      data: {
        room_id: this.data.roomInfo.id
      },
      success: (res) => {
        if (res.data.success) {
          // 检查是否没有用户
          if (res.data.data.no_users) {
            RoomUtils.navigateToHome('房间结算完成', '房间内没有用户，已自动结算')
            return
          }
          
          // 过滤掉0分的支付记录并添加时间格式化
          const filteredData = {
            ...res.data.data,
            settlement_data: res.data.data.settlement_data.map(userSettlement => ({
              ...userSettlement,
              payments: userSettlement.payments.filter(payment => payment.amount > 0).map(payment => ({
                ...payment,
                time: this.formatPaymentTime(payment.created_at || payment.time)
              })),
              expanded: false // 默认折叠其他用户的详情
            }))
          };
          
          // 分离自己和别人的结算数据
          // 尝试多种方式获取用户ID
          let currentUserId = null
          
          // 方式1：从globalData获取
          if (app.globalData && app.globalData.userInfo && app.globalData.userInfo.id) {
            currentUserId = app.globalData.userInfo.id
          }
          
          // 方式2：从本地存储获取
          if (!currentUserId) {
            try {
              const userInfo = wx.getStorageSync('userInfo')
              if (userInfo && userInfo.id) {
                currentUserId = userInfo.id
              }
            } catch (e) {
              console.log('从storage获取用户信息失败:', e)
            }
          }
          
          // 方式3：从页面参数获取
          if (!currentUserId && options.user_id) {
            currentUserId = options.user_id
          }
          
          console.log('当前用户ID:', currentUserId)
          
          const mySettlement = currentUserId ? filteredData.settlement_data.find(item => item.user_id == currentUserId) : null
          const otherSettlements = currentUserId ? filteredData.settlement_data.filter(item => item.user_id != currentUserId) : filteredData.settlement_data
          
          // 调试：打印原始数据
          console.log('原始结算数据:', filteredData.settlement_data)
          
          // 生成结算策略总结
          const settlementSummary = this.generateSettlementSummary(filteredData.settlement_data)
          
          this.setData({
            settlementData: filteredData,
            hasSettlement: true,
            mySettlement: mySettlement,
            otherSettlements: otherSettlements,
            settlementSummary: settlementSummary
          })
        } else {
          wx.showModal({
            title: '获取结算失败',
            content: res.data.message || '获取房间结算数据失败',
            showCancel: false,
            confirmText: '确定',
            success: () => {
              wx.navigateBack({
                delta: 1
              })
            }
          })
        }
      },
      fail: (err) => {
        console.error('获取房间结算失败:', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
      }
    })
  },

  // 返回上一页
  goBack() {
    // 使用工具函数清除缓存并跳转到首页
    RoomUtils.navigateToHome('房间结算完成', '已自动结算', false)
  },

  // 切换自己的详情展开/折叠
  toggleMyDetails() {
    this.setData({
      myDetailsExpanded: !this.data.myDetailsExpanded
    })
  },

  // 切换其他用户的详情展开/折叠
  toggleUserDetails(e) {
    const userId = e.currentTarget.dataset.userId
    const otherSettlements = this.data.otherSettlements.map(item => {
      if (item.user_id == userId) {
        return { ...item, expanded: !item.expanded }
      }
      return item
    })
    
    this.setData({
      otherSettlements: otherSettlements
    })
  },

  // 格式化支付时间
  formatPaymentTime(timeStr) {
    if (!timeStr) return ''
    
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    // 如果是今天
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
    
    // 如果是昨天
    const yesterday = new Date(now)
    yesterday.setDate(yesterday.getDate() - 1)
    if (date.toDateString() === yesterday.toDateString()) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
    
    // 其他情况显示日期
    return date.toLocaleDateString('zh-CN', { 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit', 
      minute: '2-digit' 
    })
  },

  // 生成结算策略总结（每个用户的具体行动）
  generateSettlementSummary(settlementData) {
    const summary = []
    
    // 计算每个用户的净分数
    const userNetScores = new Map()
    settlementData.forEach(userSettlement => {
      // 确保total_score是数字类型
      const score = parseFloat(userSettlement.total_score) || 0
      console.log('用户结算数据:', userSettlement.user_name, '原始total_score:', userSettlement.total_score, '转换后:', score, '类型:', typeof score)
      userNetScores.set(userSettlement.user_name, score)
    })
    
    console.log('用户净分数Map:', userNetScores)
    
    // 分离赢家、输家和平衡用户
    const winners = []
    const losers = []
    const balanced = []
    
    userNetScores.forEach((score, userName) => {
      if (score > 0) {
        winners.push({ name: userName, score: score })
      } else if (score < 0) {
        losers.push({ name: userName, score: Math.abs(score) })
      } else {
        balanced.push({ name: userName, score: 0 })
      }
    })
    
    // 按分数排序
    winners.sort((a, b) => b.score - a.score)
    losers.sort((a, b) => b.score - a.score)
    
    // 计算每个用户的具体行动
    const userActions = new Map()
    
    // 初始化所有用户的行动
    userNetScores.forEach((score, userName) => {
      userActions.set(userName, {
        name: userName,
        score: score,
        actions: []
      })
    })
    
    // 分配支付关系
    let winnerIndex = 0
    let loserIndex = 0
    
    while (winnerIndex < winners.length && loserIndex < losers.length) {
      const winner = winners[winnerIndex]
      const loser = losers[loserIndex]
      
      // 计算当前可以结算的金额
      const settleAmount = Math.min(winner.score, loser.score)
      
      if (settleAmount > 0) {
        // 输家需要支付给赢家
        userActions.get(loser.name).actions.push({
          type: 'pay',
          to: winner.name,
          amount: settleAmount
        })
        
        // 赢家需要从输家收取
        userActions.get(winner.name).actions.push({
          type: 'receive',
          from: loser.name,
          amount: settleAmount
        })
      }
      
      // 更新剩余分数
      winner.score -= settleAmount
      loser.score -= settleAmount
      
      // 如果某方分数为0，移动到下一个
      if (winner.score === 0) winnerIndex++
      if (loser.score === 0) loserIndex++
    }
    
    // 生成总结文本
    userActions.forEach((userAction) => {
      console.log('处理用户行动:', userAction.name, '分数:', userAction.score, '行动数量:', userAction.actions.length)
      
      if (userAction.actions.length === 0) {
        // 平衡用户
        summary.push(`📊 ${userAction.name}：积分平衡，无需支付`)
      } else if (userAction.score > 0) {
        // 赢家 - 需要收取
        const receiveActions = userAction.actions.filter(action => action.type === 'receive')
        if (receiveActions.length === 1) {
          summary.push(`💰 ${userAction.name}：收取 ${receiveActions[0].from} ${receiveActions[0].amount} 积分`)
        } else {
          const receiveList = receiveActions.map(action => `${action.from} ${action.amount}积分`).join('、')
          summary.push(`💰 ${userAction.name}：收取 ${receiveList}`)
        }
      } else if (userAction.score < 0) {
        // 输家 - 需要支付
        const payActions = userAction.actions.filter(action => action.type === 'pay')
        if (payActions.length === 1) {
          summary.push(`💸 ${userAction.name}：支付给 ${payActions[0].to} ${payActions[0].amount} 积分`)
        } else {
          const payList = payActions.map(action => `${action.to} ${action.amount}积分`).join('、')
          summary.push(`💸 ${userAction.name}：支付给 ${payList}`)
        }
      }
    })
    
    console.log('最终生成的总结:', summary)
    
    return summary
  },

  // 设置WebSocket监听
  setupWebSocketListener() {
    const WebSocketService = require('../../utils/websocketService')
    const wsService = WebSocketService.getInstance()
    
    // 监听房间结算消息
    wsService.on('room_settlement', (data) => {
      console.log('收到房间结算消息:', data)
      
      // 如果消息包含自动跳转信息
      if (data.auto_navigate && data.navigate_url) {
        wx.showModal({
          title: '房间结算完成',
          content: data.message || '房间已自动结算完成',
          showCancel: false,
          confirmText: '查看结算结果',
          success: () => {
            // 跳转到结算结果页面
            wx.navigateTo({
              url: data.navigate_url,
              fail: () => {
                // 如果跳转失败，刷新当前页面
                this.getRoomSettlement()
              }
            })
          }
        })
      }
    })
  },

  // 分享给好友
  async onShareAppMessage() {
    return {
      title: '房间结算详情',
      path: `/pages/room-settlement/room-settlement?room_id=${this.data.roomInfo.id}`,
      imageUrl: '/images/share-room.jpg'
    }
  }
})
